class CommentsController {
    def securityService

    def index = { }

    def list = { 
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [commentsInstanceList: Comments.findAllByParent(securityService.getCurrentUser(),[sort:"createTime", order:"desc"] ), commentsInstanceTotal: Comments.countByParent(securityService.getCurrentUser()),site:securityService.getCurrentUser().student.site]
    }

    def create = {
    
    
    }

    def edit = {
        def commentsInstance = Comments.get(params.id)
        if (!commentsInstance) {
            flash.message = "没有找到此问题"
            redirect(action: "list")
        }
        else {
            return [commentsInstance: commentsInstance]
        }
    }

    def update = {
        def commentsInstance = Comments.get(params.id)
        if (commentsInstance) {
            commentsInstance.properties = params
            if (!commentsInstance.hasErrors() && commentsInstance.save(flush: true)) {
                flash.message = "更新成功"
                redirect(action: "list")
            }
            else {
                flash.message = "更新失败"
                render(view: "edit", model: [commentsInstance: commentsInstance])
            }
        }
        else {
            flash.message = "没有找到此问题"
            redirect(action: "list")
        }
    }

    def delete = {
        def commentsInstance = Comments.get(params.id)
        if (commentsInstance) {
            try {
                commentsInstance.delete(flush: true)
                flash.message = "删除成功"
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "删除错误"
                redirect(action: "show", id: params.id)
            }
        }
        else {
            flash.message = "没有找到此问题"
            redirect(action: "list")
        }
    }

    def save = {
            def commentsInstance = new Comments(params)
            def user = securityService.getCurrentUser()
            commentsInstance.parent = user
            commentsInstance.parentName = user.name
            commentsInstance.classId = user.student.classesId.toLong()
            log.info(user)
            log.info(user.student.classesId)
            if(commentsInstance.validate()) {
                // do something with user
            }else {
                commentsInstance.errors.allErrors.each {
                    println it
                }
            }

            if (commentsInstance.save(flush: true)) {
                flash.message = "发送成功"
                redirect(action: "list")
            }
            else {
                render(view: "create", model: [commentsInstance: commentsInstance])
            }
        }
}
